import React, { useRef, useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Card, Space, message, Popconfirm, Dropdown, Menu } from 'antd';
import ProTable from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import request from '@/utils/request';
import { connect } from 'umi';
import FolderTree from './components/FolderTree';
import FileTypeTree from './components/FileTypeTree';
import NewDocModal from './components/NewDocModal';
import Uploader from '@/components/Uploader';

const Resources = (props) => {
  const { dispatch } = props;

  const actionRef = useRef();

  const [visible, setVisible] = useState(false);
  const [type, setType] = useState();
  const [fid, setFid] = useState();
  const [ext, setExt] = useState();
  const [deleted, setDeleted] = useState(false);

  const columns = [
    {
      title: '文件ID',
      dataIndex: 'rid',
      copyable: true,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '文件名称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
      fixed: 'left',
    },
    {
      title: '作者',
      dataIndex: 'username',
      hideInSearch: true,
      copyable: true,
      width: 100,
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'ext',
      onFilter: true,
      hideInSearch: true,
      width: 80,
      valueType: 'select',
      valueEnum: {
        '': { text: '全部', status: '' },
        docx: {
          text: 'Word',
          status: 'docx',
        },
        excel: {
          text: 'Excel',
          status: 'excel',
        },
        pptx: {
          text: 'PPT',
          status: 'pptx',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'datetime',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      width: 100,
      render: (text, record, _, action) => {
        if (record.deleted) {
          return (
            <Popconfirm
              key="del"
              title="确认要恢复此文档吗?"
              onConfirm={() => {
                dispatch({
                  type: 'resources/undel',
                  payload: { rid: record.rid },
                  callback: (res) => {
                    if (res.success) {
                      action.reload();
                    } else {
                      message.error(res.msg);
                    }
                  },
                });
              }}
            >
              <a href="#">恢复</a>
            </Popconfirm>
          );
        }

        return (
          <Space size="middle">
            <a
              key="open"
              target="_blank"
              rel="noopener noreferrer"
              href={`./#/office?rid=${record.rid}`}
            >
              打开
            </a>
            <Uploader
              key="newversion"
              type="link"
              icon={false}
              action={`/eofficeserver/api/resource/upload?rid=${record.rid}`}
              afterUpload={() => actionRef.current.reload()}
              text="更新"
              accept={record.ext}
            />
            <Dropdown
              overlay={() => (
                <Menu
                  onClick={({ key }) => {
                    switch (key) {
                      case 'rename':
                        window.open('record.url', '_blank');
                        break;
                      default:
                        console.error('unsupport key', key);
                    }
                  }}
                >
                  <Menu.Item key="rename" disabled>
                    重命名
                  </Menu.Item>
                  <Menu.Item disabled key="history">
                    历史
                  </Menu.Item>
                  <Menu.Item disabled key="share">
                    分享
                  </Menu.Item>
                  <Menu.Divider />
                  <Menu.Item danger>
                    <Popconfirm
                      key="del"
                      title="确认要删除此文档吗?"
                      onConfirm={() => {
                        dispatch({
                          type: 'resources/del',
                          payload: { rid: record.rid },
                          callback: (res) => {
                            if (res.success) {
                              action.reload();
                            } else {
                              message.error(res.msg);
                            }
                          },
                        });
                      }}
                    >
                      <a href="#">删除</a>
                    </Popconfirm>
                  </Menu.Item>
                </Menu>
              )}
            >
              <a className="ant-dropdown-link" onClick={(e) => e.preventDefault()}>
                其他 <DownOutlined />
              </a>
            </Dropdown>
          </Space>
        );
      },
    },
  ];

  const showModal = ({ key }) => {
    setType(key);
    setVisible(true);
  };

  const menu = (
    <Menu onClick={showModal}>
      <Menu.Item key="docx">新建Word</Menu.Item>
      <Menu.Item key="xlsx">新建Excel</Menu.Item>
      <Menu.Item key="pptx">新建PPT</Menu.Item>
    </Menu>
  );

  const onCreate = (values) => {
    setVisible(false);
    // 创建一个资源，返回资源ID
    dispatch({
      type: 'resources/add',
      payload: { tid: values.tid, ext: type, type: 'document', name: values.name, fid },
      callback: (res) => {
        setTimeout(() => {
          actionRef.current.reload();
        }, 1000);
        window.open(`./#office/view?rid=${res.data.rid}`, '_blank');
      },
    });
  };

  return (
    <PageContainer title={false}>
      <ProTable
        scroll={{ x: 800 }}
        columns={columns}
        actionRef={actionRef}
        request={async (params, sort, filter) => {
          const response = await request('/eofficeserver/api/resource', {
            params: { ...filter, ...params, fid, ext, deleted },
          });

          if (!response.success) {
            return {
              data: [],
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: 0,
            };
          }

          return {
            data: response.data.list,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: response.data.pagination.total,
          };
        }}
        editable={{
          type: 'multiple',
        }}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <Card title={false}>
              <FolderTree
                onNodeSelect={(folderid) => {
                  if (folderid === 'recyclebin') {
                    setDeleted(true);
                  } else {
                    setFid(folderid);
                    setDeleted(false);
                  }

                  actionRef.current.reload();
                }}
              />
              <FileTypeTree
                onNodeSelect={(extension) => {
                  setExt(extension);
                  actionRef.current.reload();
                }}
              />
            </Card>
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        rowKey="rid"
        search={false}
        pagination={{
          showQuickJumper: true,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Uploader
            key="upload"
            action={`/eofficeserver/api/resource/upload?fid=${fid || ''}`}
            afterUpload={() => actionRef.current.reload()}
            text="上传"
            accept=".doc,.docx,.xlsx,.xls,.pptx,.ppt"
          />,
          <Dropdown overlay={menu} key="create">
            <Button type="primary" onClick={(e) => e.preventDefault()}>
              新建 <DownOutlined />
            </Button>
          </Dropdown>,
        ]}
      />
      {visible && (
        <NewDocModal
          type={type}
          label="文档名称"
          visible={visible}
          onCreate={onCreate}
          onCancel={() => {
            setVisible(false);
          }}
        />
      )}
    </PageContainer>
  );
};

export default connect(({ resources, user, loading }) => ({
  resources,
  currentUser: user.currentUser,
  deling: loading.effects['resources/del'],
}))(Resources);
